<template>
  <div class="form__container">
    <t-loading text="加载中..." size="small" v-if="pageData.loading" />
    <div style="height: 100%; overflow: hidden">
      <t-row v-if="!pageData.loading">
        <t-col :span="2"
          ><t-tree
            :data="pageData.treeTabs"
            activable
            hover
            :expandAll="true"
            @click="handleTreeChange"
            :defaultValue="['foreign_basicinfo']"
            v-model:actived="pageData.treeActiveArr"
        /></t-col>
        <t-col :span="10">
          <!-- 国外主体-基本信息 -->
          <AbroadBasicInfo
            v-if="pageData.activeTab === 'foreign_basicinfo'"
            @update-data="handleUpdateData"
            :formData="pageData.formData"
            :readOnly="pageData.readOnly"
          />

          <!-- 国外主体-联系人 -->
          <AbroadContact
            v-if="pageData.activeTab === 'foreign_contact'"
            @update-data="handleUpdateData"
            :formData="pageData.formData"
            :readOnly="pageData.readOnly"
          />

          <!-- 国外主体-资质文件 -->
          <AbroadQualifications
            v-if="pageData.activeTab === 'foreign_qualifications'"
            @update-data="handleUpdateData"
            :formData="pageData.formData"
            :readOnly="pageData.readOnly"
            :mode="props.mode"
          />

          <!-- 国外主体-网店信息 -->
          <AbroadShop
            v-if="pageData.activeTab === 'foreign_shop'"
            @update-data="handleUpdateData"
            :formData="pageData.formData"
            :readOnly="pageData.readOnly"
          />

          <!-- 国内主体-基本信息 -->
          <ChinaBasicInfo
            v-if="pageData.activeTab === 'china_basicinfo'"
            @update-data="handleUpdateData"
            :formData="pageData.formData"
            :readOnly="pageData.readOnly"
          />

          <!-- 国内主体-联系人 -->
          <ChinaContact
            v-if="pageData.activeTab === 'china_contact'"
            @update-data="handleUpdateData"
            :formData="pageData.formData"
            :readOnly="pageData.readOnly"
          />

          <!-- 国内主体-工商信息 -->
          <ChinaIndustryAndCommerce
            v-if="pageData.activeTab === 'china_industry'"
            @update-data="handleUpdateData"
            :formData="pageData.formData"
            :readOnly="pageData.readOnly"
          />

          <!-- 国内主体-资质文件 -->
          <ChinaQualifications
            v-if="pageData.activeTab === 'china_qualifications'"
            @update-data="handleUpdateData"
            :formData="pageData.formData"
            :readOnly="pageData.readOnly"
            :mode="props.mode"
          />

          <!-- 其他信息-备注 -->
          <OtherRemark
            v-if="pageData.activeTab === 'other_remark'"
            @update-data="handleUpdateData"
            :formData="pageData.formData"
            :readOnly="pageData.readOnly"
          />
          <div class="form__container"></div>
        </t-col>
      </t-row>
    </div>
  </div>
</template>

<script lang="tsx" setup>
// 框架和组件库
import { reactive, defineAsyncComponent } from "vue";
// import { MessagePlugin } from "tdesign-vue-next";

// 工具函数
import { http } from "@/utils/fetch";
import { generateFormattedNumber } from "@/utils/tools";
import { v4 as uuidv4 } from "uuid";

// API
// import { deleteFileMany } from "@/api/file";

// 业务组件
// import { useUserStore } from "@/stores/modules/user";

// 动态组件
const AbroadBasicInfo = defineAsyncComponent(
  () => import("@/pages/Dashboard/CAS/Customer/components/Abroad/BasicInfo.vue")
);
const AbroadContact = defineAsyncComponent(
  () => import("@/pages/Dashboard/CAS/Customer/components/Abroad/Contact.vue")
);
const AbroadQualifications = defineAsyncComponent(
  () => import("@/pages/Dashboard/CAS/Customer/components/Abroad/Qualifications.vue")
);
const AbroadShop = defineAsyncComponent(() => import("@/pages/Dashboard/CAS/Customer/components/Abroad/Shop.vue"));
const ChinaBasicInfo = defineAsyncComponent(
  () => import("@/pages/Dashboard/CAS/Customer/components/China/BasicInfo.vue")
);
const ChinaIndustryAndCommerce = defineAsyncComponent(
  () => import("@/pages/Dashboard/CAS/Customer/components/China/IndustryAndCommerce.vue")
);
const ChinaQualifications = defineAsyncComponent(
  () => import("@/pages/Dashboard/CAS/Customer/components/China/Qualifications.vue")
);
const ChinaContact = defineAsyncComponent(() => import("@/pages/Dashboard/CAS/Customer/components/China/Contact.vue"));
const OtherRemark = defineAsyncComponent(() => import("@/pages/Dashboard/CAS/Customer/components/Other/Remark.vue"));

const props = defineProps({
  id: {
    type: String,
    required: true
  },
  // dialogVisible: {
  //   type: Boolean,
  //   default: false
  // },
  mode: {
    type: String,
    required: true
  }
});

// const emits = defineEmits(["close"]);

// const formInstance = ref<FormInstanceFunctions | null>(null);

const GET_FORM_PATH = "/customer/findOne"; // 查询接口
// const CREATE_FORM_PATH = "/customer/create"; // 创建接口
// const UPDATE_FORM_PATH = "/customer/update"; // 更新接口

// const userStore = useUserStore();

const pageData = reactive({
  loading: true,
  readOnly: false,
  formData: {
    registerLimitTime: [],
    id: "",
    createdTime: "",
    createdBy: "",
    status: 0,
    remark: "",
    updatedBy: "",
    updatedTime: "",
    createdByName: "",
    updatedByName: "",
    hasDeleted: 0,
    englishName: "",
    englishNickname: "",
    englishAddress: "",
    countryId: "",
    countryName: "",
    customsId: "",
    mainBusiness: "",
    market: "",
    name: "",
    nickName: "",
    address: "",
    province: "",
    city: "",
    chinaMainBusiness: "",
    chinaMainMarket: "",
    creditCode: "",
    legalPerson: "",
    registerName: "",
    type: "",
    registerTime: "",
    registerLimitTimeStart: "",
    registerLimitTimeEnd: "",
    registerMoney: "",
    registerAddress: "",
    registerBusiness: "",
    registerLicenseId: "",
    onlineShops: [],
    contacts: [],
    globalContacts: [],
    registerLicense: {},
    customerName: "",
    customerNo: "",
    qualificationFiles: [],
    globalQualificationFiles: [],
    deletedQualFileIds: []
  } as Record<string, any>,
  formRules: {},
  activeTab: "foreign_basicinfo",
  treeActiveArr: ["foreign_basicinfo"],
  treeTabs: [
    {
      label: "国外主体信息",
      value: "foreign",
      children: [
        {
          label: "基本信息",
          value: "foreign_basicinfo"
        },
        {
          label: "联系人信息",
          value: "foreign_contact"
        },
        {
          label: "资质文件",
          value: "foreign_qualifications"
        },
        {
          label: "网店信息",
          value: "foreign_shop"
        }
      ]
    },
    {
      label: "国内主体信息",
      value: "china",
      children: [
        {
          label: "基本信息",
          value: "china_basicinfo"
        },
        {
          label: "联系人信息",
          value: "china_contact"
        },
        {
          label: "工商信息",
          value: "china_industry"
        },
        {
          label: "资质文件",
          value: "china_qualifications"
        }
      ]
    },
    {
      label: "其他",
      value: "other",
      children: [
        {
          label: "备注",
          value: "other_remark"
        }
      ]
    }
  ]
});

/**
 * 初始化表单数据。
 * 根据不同的操作模式（新增、编辑、查看），加载不同的数据。
 * @param id - ID，用于编辑和查看模式下查询信息。
 */
const initFormData = async (id = "") => {
  if (props.mode !== "new") {
    // } else if (props.mode === "edit" || props.mode === "view") {
    const resultData = await http("GET", `${GET_FORM_PATH}?id=${encodeURIComponent(id)}`);
    pageData.formData = resultData.data;

    // 给每一个联系人本地数据加一个 localUUID，方便识别
    if (pageData.formData.contacts.length > 0 && !pageData.formData.contacts.some((item: null) => item === null)) {
      pageData.formData.contacts.forEach((item: any) => {
        item.localUUID = uuidv4();
      });
    }

    if (
      pageData.formData.onlineShops.length > 0 &&
      !pageData.formData.onlineShops.some((item: null) => item === null)
    ) {
      pageData.formData.onlineShops.forEach((item: any) => {
        item.localUUID = uuidv4();
      });

      pageData.formData.deletedQualFileIds = [];
    } else {
      pageData.formData.onlineShops = [];
    }

    if (
      pageData.formData.qualificationFiles.length === 0 &&
      pageData.formData.qualificationFiles.some((item: null) => item === null)
    ) {
      pageData.formData.qualificationFiles = [];
    }

    pageData.formData.registerLimitTime = [
      pageData.formData.registerLimitTimeStart,
      pageData.formData.registerLimitTimeEnd
    ];

    pageData.formData.countryName = pageData.formData.country?.countryName;

    pageData.loading = false;

    if (props.mode === "view") {
      pageData.readOnly = true;
    }
  } else {
    pageData.loading = false;
    pageData.formData.customerNo = `KH${generateFormattedNumber()}`;
  }
};

const handleUpdateData = (newData: Record<string, any>) => {
  pageData.formData = { ...pageData.formData, ...newData };
};

const handleTreeChange = (e: Record<string, any>) => {
  pageData.activeTab = e.node.value;
};

/**
 * 提交表单。
 * 根据不同的操作模式（新增、编辑），调用不同的接口保存信息。
 */
// const handleSubmit = async () => {
//   let resultData;

//   if (props.mode === "view") {
//     handleClose();
//     return;
//   }

//   // console.log(toRaw(pageData.formData));
//   const postFormData = toRaw(pageData.formData);

//   if (postFormData.onlineShops.length === 0) {
//     MessagePlugin.error("网店信息不能为空！");
//     return;
//   }

//   if (postFormData.contacts.length === 0) {
//     MessagePlugin.error("联系人信息不能为空！");
//     return;
//   }

//   if (postFormData.qualificationFiles.length === 0) {
//     MessagePlugin.error("资质文件信息不能为空！");
//     return;
//   } else {
//     postFormData.qualificationFileIds = postFormData.qualificationFiles.map((item: Record<string, any>) => item.id);
//     postFormData.globalQualificationFileIds = postFormData.globalQualificationFiles.map(
//       (item: Record<string, any>) => item.id
//     );
//   }

//   if (postFormData.deletedQualFileIds.length > 0) {
//     await deleteFileMany({ deleteIds: postFormData.deletedQualFileIds });
//   }

//   if (props.mode === "new") {
//     // 新增
//     resultData = await http("POST", CREATE_FORM_PATH, postFormData);
//   } else {
//     // 更新
//     // postFormData.updatedTime = new Date().toISOString();
//     // postFormData.updatedBy = userStore.userData?.id;

//     resultData = await http("POST", UPDATE_FORM_PATH, postFormData);
//   }

//   // 根据接口返回结果，提示操作成功或失败，并关闭对话框
//   if (resultData.code === 200) {
//     emits("close", "success");
//   }
// };

// const handleClose = () => {
//   // 关闭对话框，并返回取消操作标识
//   emits("close", "cancel");
// };

// 如果是查看模式，设置表单为只读
if (props.mode == "view") {
  pageData.readOnly = true;
}

// 初始化表单数据，根据传入的 ID
initFormData(props.id);
</script>
